<?php
namespace Admin\Model;

class SysChannelModel extends SystemModel
{
    //调用配置文件中的数据库配置
    protected $connection = 'BLOCKER_DATABASE';
	protected $trueTableName = "sys_channel";
	protected $_pk = 'id';
	
	public $ad_type = [
		1 => "显示广告",
		2 => "点击广告",
	];
	
	public $_auto		=	array(
			array('create_at','time',self::MODEL_INSERT,'function'),
			array('admin_id','admin_id',self::MODEL_INSERT,'function'),
	);
	
	protected $_validate = array(
			array('name','','渠道名称已经存在！',self::MODEL_INSERT,'unique',1),
			array('name','require','英文名称不能为空'),
			array('cname','require','中文名称不能为空'),
	);

	/**
	 * 获取当前登录者渠道名称
	 * 
	 * @param int $channelid 渠道id
	 * @author allenqin<allenqinhai@gmail.com>
	 */
	public function getChannelName($channelid = NULL)
	{
		$map['id'] = $channelid ? $channelid : admin_channel_id();
		return $this->where($map)->cache(true, 3600)->getField('name');
	}

	/**
	 * 通过渠道名称获取渠道id
	 * @param   $channel_name   渠道名称
	 * @return  $channel_id     渠道id
	 */
	public function channelNameToId($channel_name)
	{
		$channel_id_name = $this->getChannelList();
		$channel_id = array_keys($channel_id_name, $channel_name)[0];
		return isset($channel_id) ? intval($channel_id) : 0;
	}
	
	/**
	 * 根据应用id获取应用所属仓库
	 * 
	 * @param int $aid 应用id
	 * @author allenqin<allenqinhai@gmail.com>
	 */
	public function getChannelNameByAid($aid)
	{
		$channelid = M('AppsStatic')->cache('BY_APPID_GET_CHANNELID_' . $aid, 3600)->where(array('sid' => $aid))->getField('channelid');
		return $this->getChannelName($channelid);
	}
	
	/**
	 * 获得渠道id和渠道缓存
	 */
	public function getChannelList()
	{
		$key = $this->getChannelListKey();
		$data = S($key);
		$data = json_decode(gzuncompress($data), true);
		return $data;
	}
	
	/**
	 * 创建渠道id和渠道缓存
	 */
	public function createChannelList()
	{
		$key = $this->getChannelListKey();
		$data = $this->where(['status'=>1])->getField('id, name', true);
		$data = gzcompress(json_encode($data));
		$is_cache = S($key, $data);
		return ($is_cache==1) ? true : false;
	}
	
	/**
	 * 缓存渠道id和渠道key
	 */
	public function getChannelListKey()
	{
		return "ad_channel_list";
	}
	
}